package com.ruoyi.manage.organization.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.ListUtil;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.NumsUtils;
import com.ruoyi.manage.enterprise.domain.SysUserExpand;
import com.ruoyi.manage.enterprise.service.ISysUserExpandService;
import com.ruoyi.manage.organization.domain.BizOrganization;
import com.ruoyi.manage.organization.domain.BizOrganizationAudit;
import com.ruoyi.manage.organization.domain.BizOrganizationMember;
import com.ruoyi.manage.organization.domain.vo.BizOrganizationVo;
import com.ruoyi.manage.organization.mapper.BizOrganizationMapper;
import com.ruoyi.manage.organization.service.IBizOrganizationAuditService;
import com.ruoyi.manage.organization.service.IBizOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 金融机构信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-15
 */
@Service
public class BizOrganizationServiceImpl extends ServiceImpl<BizOrganizationMapper, BizOrganization> implements IBizOrganizationService {

    @Autowired
    private IBizOrganizationAuditService bizOrganizationAuditService;

    @Autowired
    private ISysUserExpandService iSysUserExpandService;

    @Autowired
    private ISysUserExpandService expandService;

    @Override
    public BizOrganization queryGetById(String id) {
        BizOrganization bizOrganization = this.getById(id);
        bizOrganization.setBizOrganizationAuditList(bizOrganizationAuditService.list(new QueryWrapper<BizOrganizationAudit>().eq("org_id", id)));
        return bizOrganization;
    }

    @Override
    public List<BizOrganizationVo> lists(QueryWrapper wrapper) {
        List<BizOrganizationVo> vo = baseMapper.selectLists(wrapper);
        return vo;
    }

    @Override
    public List<BizOrganizationVo> selectOrganizationName() {
        List<BizOrganizationVo> vo = baseMapper.selectOrganizationName();
        return vo;
    }

    @Override
    public String selectOrganizationIdByUser(Long userId) {
        SysUserExpand expand  = expandService.getOne(new QueryWrapper<SysUserExpand>().eq("user_id", userId));
        if(expand != null){
            return String.valueOf(expand.getRelatedId());
        }
        return null;
    }


    @Override
    public List<Tree<Long>> getNodeTree() {
        List<BizOrganization> nodeList = this.list();
        List<TreeNode> transNodes = nodeList.stream().map(m -> new TreeNode(m.getId(), m.getParentId(), m.getOrgName(), "")).collect(Collectors.toList());
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
// 自定义属性名 都有默认值的
        treeNodeConfig.setNameKey("label");
        treeNodeConfig.setIdKey("value");
// 最大递归深度

//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<Long>> treeNodes = TreeUtil.<TreeNode, Long>build(transNodes, 0L, treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId((Long) treeNode.getId());
                    tree.setParentId((Long) treeNode.getParentId());
                    tree.setWeight(treeNode.getWeight());
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                });
        return treeNodes;
    }

    /**
     * 新增金融机构信息
     *
     * @param bizOrganization 金融机构信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addBizOrganization(BizOrganization bizOrganization) {
        bizOrganization.setVersion("0");
        boolean save = this.save(bizOrganization);
        insertBizOrganizationAudit(bizOrganization);
        return save;
    }

    @Override
    public boolean addBizOrganizationByApp(BizOrganization bizOrganization) {
//        生成机构orgcode，如果存在父id则获取父类的路劲code,拼接到一起
        bizOrganization.setOrgCode(NumsUtils.generateCode("G"));
        bizOrganization.setOrgPath("/" + bizOrganization.getOrgCode());
        bizOrganization.setVersion("2");
        bizOrganization.setLevel(1);

        if (ObjUtil.isNotNull(bizOrganization.getParentId())) {
            BizOrganization bizParent = this.getById(bizOrganization.getParentId());
            bizOrganization.setOrgPath(bizParent.getOrgPath() + bizOrganization.getOrgPath());
            Integer level = bizParent.getLevel();
            bizOrganization.setLevel(level + 1);
        }
        boolean save = this.save(bizOrganization);
        insertBizOrganizationAudit(bizOrganization);
        return save;
    }

    @Override
    public boolean updateBizOrganizationByApp(BizOrganization bizOrganization) {
        boolean b = this.updateById(bizOrganization);
        return b;
    }

    /**
     * 修改金融机构信息
     *
     * @param bizOrganization 金融机构信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateBizOrganization(BizOrganization bizOrganization) {
        bizOrganization.setVersion(Integer.valueOf(bizOrganization.getVersion()).intValue() + 1 + "");
        bizOrganizationAuditService.remove(new LambdaUpdateWrapper<BizOrganizationAudit>().eq(BizOrganizationAudit::getOrgId, bizOrganization.getId()));
        insertBizOrganizationAudit(bizOrganization);
        return this.updateById(bizOrganization);
    }

    /**
     * 批量删除金融机构信息
     *
     * @param ids 需要删除的金融机构信息主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteBizOrganizationByIds(String[] ids) {
        bizOrganizationAuditService.remove(new LambdaUpdateWrapper<BizOrganizationAudit>().in(BizOrganizationAudit::getOrgId, ids));
        return this.removeByIds(ListUtil.toList(ids));
    }


    /**
     * 新增金融机构审核信息
     *
     * @param bizOrganization 金融机构信息对象
     */
    public void insertBizOrganizationAudit(BizOrganization bizOrganization) {

        BizOrganizationAudit audit = new BizOrganizationAudit();
        audit.setOrgId(bizOrganization.getId());
        bizOrganizationAuditService.save(audit);

    }

    /**
     * 审核金融机构信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void check(BizOrganizationVo bizOrganization) {

        bizOrganizationAuditService.update(new LambdaUpdateWrapper<BizOrganizationAudit>().eq(BizOrganizationAudit::getOrgId, bizOrganization.getId())
                .set(BizOrganizationAudit::getAudit, bizOrganization.getAudit()).set(BizOrganizationAudit::getAuditDesc, bizOrganization.getAuditDesc())
                .set(BizOrganizationAudit::getAuditTime, new Date()));


        /*BizOrganizationAudit audit = bizOrganizationAuditService.getOne(new QueryWrapper<BizOrganizationAudit>().eq("org_id",bizOrganization.getId()));
        if(audit != null){
            audit.setAudit(bizOrganization.getAudit());
            audit.setAuditDesc(bizOrganization.getAuditDesc());
            audit.setAuditTime(new Date());
        }*/
    }

    @Override
    public List<BizOrganizationMember> selectOrganizationMember(QueryWrapper wrapper) {
        wrapper.eq("u.user_type", 1);
        List<SysUserExpand> userExpandList = iSysUserExpandService.list(new QueryWrapper<SysUserExpand>().select("related_id").eq("user_id", SecurityUtils.getUserId()).eq("user_type", 1));
        List<Long> selectIds = userExpandList.stream().map(m -> m.getRelatedId()).collect(Collectors.toList());
        if (selectIds.size() > 0) {
            wrapper.in("e.related_id", selectIds);
            List<BizOrganizationMember> organizationMembers = baseMapper.selectOrganizationMember(wrapper);
            return organizationMembers;
        }

        return Collections.emptyList();
    }

    @Override
    public List<BizOrganizationMember> selectOrganizationMember2(QueryWrapper wrapper) {
        wrapper.eq("u.user_type", 1);
        List<BizOrganizationMember> organizationMembers = baseMapper.selectOrganizationMember(wrapper);
        return organizationMembers;
    }
}
